<template>
  <div class="echartsBox">
    <div class="nav">
      <div class="nav_left">
        摄氏度(℃)
        <div class="select" @click="showPicker = true">
          {{ pickerText }}年<van-icon name="arrow-down" />
        </div>
      </div>
      <div class="nav_right">
        <div class="legend_item">
          <div class="item_icon_green" />
          <div class="desc">10cm</div>
        </div>
        <div class="legend_item">
          <div class="item_icon_orange" />
          <div class="desc">40cm</div>
        </div>
      </div>
    </div>
    <div id="temperature_echarts" class="echarts" />

    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        :columns="columns"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>
  </div>
</template>

<script>
import { http_farmland } from '@/api';
export default {
  props: ['fieldId', 'yAxis', 'xAxis'],
  data() {
    return {
      showPicker: false,
      pickerText: '',
      columns: []
    };
  },
  mounted() {
    const year = new Date().getFullYear();
    this.pickerText = year.toString();
    this.getYear();
    this.getFieldSoilMoisture();
  },
  methods: {
    getYear() {
      // 获取年份，当前年前后5年
      var y = new Date().getFullYear();
      const years = [];
      for (var i = 0; i <= 5; i++) {
        if (i < 5) {
          years.unshift(y - i);
        }
      }
      this.columns = years;
    },
    onConfirm(value) {
      this.pickerText = value;
      this.showPicker = false;
      this.getFieldSoilMoisture();
    },
    async getFieldSoilMoisture() {
      const params = {
        lat: this.yAxis,
        lng: this.xAxis,
        fieldId: this.fieldId,
        year: this.pickerText
      };
      const result = await http_farmland.temp_detail(params);
      if (result.resCode == 0) {
        this.soilTemperatureEcharts(result.resData);
      } else {
        this.$toast(result.errCode);
      }
    },
    // 画图表 土壤温度
    soilTemperatureEcharts(data) {
      var moisture = data.temperature;
      var xdata = moisture.date; // 日期
      var ydataA = moisture.layer1; // 温度10cm
      var ydataB = moisture.layer2; // 温度40cm
      var marklineArr = data.temp_over10; // 竖向的标记线

      // 警戒线
      var temp_line = 10;

      /**
       * 获取当日在日期数组中的下标
       */
      var curDayIndex;
      for (var i = 0; i < xdata.length; i++) {
        var xItem = xdata[i].toString();
        var year = xItem.substr(0, 4);
        var month = xItem.substr(4, 2);
        var monthFormat = month.substr(0, 1) == 1 ? month : month.substr(1, 1);
        var day = xItem.substr(6, 2);
        var curYear = new Date().getFullYear();
        var curMonth = new Date().getMonth() + 1;
        var curDay = new Date().getDate();
        if (curYear == year && curMonth == monthFormat && curDay == day) {
          curDayIndex = i;
          break;
        }
      }

      var ydataAA = [];
      var ydataAAFuture = []; // 预测折线
      if (ydataA) {
        // 既有实线，也有虚线
        if (curDayIndex == 0 || curDayIndex) {
          for (var i = 0; i < ydataA.length; i++) {
            var arr = (ydataA[i] - 273.15).toFixed(2);
            //  实线部分
            if (i < curDayIndex) {
              ydataAA.push(arr);
              ydataAAFuture.push('');
            }
            //  虚实相接的点
            if (i == curDayIndex) {
              ydataAA.push(arr);
              ydataAAFuture.push(arr);
            }
            //  虚线部分
            if (i > curDayIndex) {
              ydataAA.push('');
              ydataAAFuture.push(arr);
            }
          }
        } else {
          // 只有实线
          for (var i = 0; i < ydataA.length; i++) {
            var arr = (ydataA[i] - 273.15).toFixed(2);
            ydataAA.push(arr);
          }
        }
      }

      var ydataBB = [];
      var ydataBBFuture = []; // 预测折线
      if (ydataB) {
        // 既有实线，也有虚线
        if (curDayIndex == 0 || curDayIndex) {
          for (var i = 0; i < ydataB.length; i++) {
            var arr = (ydataB[i] - 273.15).toFixed(2);
            //  实线部分
            if (i < curDayIndex) {
              ydataBB.push(arr);
              ydataBBFuture.push('');
            }
            //  虚实相接的点
            if (i == curDayIndex) {
              ydataBB.push(arr);
              ydataBBFuture.push(arr);
            }
            //  虚线部分
            if (i > curDayIndex) {
              ydataBB.push('');
              ydataBBFuture.push(arr);
            }
          }
        } else {
          // 只有实线
          for (var i = 0; i < ydataB.length; i++) {
            var arr = (ydataB[i] - 273.15).toFixed(2);
            ydataBB.push(arr);
          }
        }
      }

      var dom = document.getElementById('temperature_echarts');
      var myChartscen = this.$echarts.init(dom);
      var option = {
        color: ['#509be6', '#ffc100', '#f26166', '#ad70cc'],
        grid: {
          show: true,
          left: '3%',
          top: '3%',
          right: '3%',
          bottom: '3%',
          containLabel: true,
          backgroundColor: 'rgba(242, 242, 243, 1)',
          borderColor: 'rgba(144, 144, 153, 1)',
          borderWidth: '1'
        },
        dataZoom: [
          {
            show: true,
            height: '1%',
            xAxisIndex: [0],
            bottom: '-4%',
            startValue: 0,
            endValue: xdata.length - 1,
            handleIcon:
              'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
            handleSize: '100%',
            handleStyle: {
              color: '#d3dee5'
            },
            textStyle: {
              color: '#000'
            },
            borderColor: '#90979c'
          },
          {
            type: 'inside',
            show: true,
            height: 15,
            startValue: 0,
            endValue: xdata.length - 1
          }
        ],
        tooltip: {
          trigger: 'axis',
          confine: true,
          formatter: function(params) {
            // 自定义函数修改折线图给数据加单位
            var curDate = params[0]['name'];
            var year = curDate.substr(0, 4);
            var month = curDate.substr(4, 2);
            var day = curDate.substr(6, 2);
            var formatDate = year + '.' + month + '.' + day;
            var temp_10 = '';
            var temp_40 = '';
            var curIndex;
            for (var d = 0; d < xdata.length; d++) {
              if (xdata[d] == curDate) {
                curIndex = d;
                break;
              }
            }
            temp_10 = (parseFloat(ydataA[curIndex]) - 273.15).toFixed(2);
            temp_40 = (parseFloat(ydataB[curIndex]) - 273.15).toFixed(2);
            var dom =
              '<div class="tooltip-wrap2">' +
              '<div class="wrap-date">' +
              formatDate +
              '</div>' +
              '<div class="wrap-line"></div>' +
              '<div class="wrap-item">' +
              '<div class="item-icon-unit-con">' +
              '<div class="item-icon green"></div>' +
              '<div class="item-unit">10cm(℃)</div>' +
              '</div>' +
              ' <div class="item-val">' +
              temp_10 +
              '</div>' +
              '</div>' +
              '<div class="wrap-item">' +
              '<div class="item-icon-unit-con">' +
              '<div class="item-icon orange"></div>' +
              '<div class="item-unit">40cm(℃)</div>' +
              '</div>' +
              '<div class="item-val">' +
              temp_40 +
              '</div>' +
              '</div>' +
              '</div>';
            return dom;
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: true,
          axisLabel: {
            show: true,
            textStyle: {
              color: '#000'
            },
            // interval: 0,
            formatter: function(value, index) {
              var month = value.substr(4, 2);
              var day = value.substr(6, 2);
              var monthFormat =
                month.substr(0, 1) == 1 ? month : month.substr(1, 1);
              var formatDate = monthFormat + '.' + day;
              return formatDate;
            }
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: false
          },
          data: xdata
        },
        yAxis: [
          {
            type: 'value',
            axisLabel: {
              show: true,
              textStyle: {
                color: '#000'
              }
            },
            axisTick: {
              show: false
            },
            splitLine: {
              show: true
            }
          }
        ],
        series: [
          {
            id: 'temp_10',
            name: '摄氏度(℃)(10CM)',
            type: 'line',
            smooth: true,
            itemStyle: {
              normal: {
                lineStyle: {
                  color: 'rgba(50,196,94,1)'
                }
              }
            },
            yAxisIndex: 0,
            data: ydataAA
          },
          {
            id: 'temp_40',
            name: '摄氏度(℃)(40CM)',
            type: 'line',
            smooth: true,
            itemStyle: {
              normal: {
                lineStyle: {
                  color: 'rgba(255,167,28,1)'
                }
              }
            },
            yAxisIndex: 0,
            data: ydataBB,
            markLine: {
              symbol: 'none',
              label: {
                show: false,
                position: 'end',
                color: 'rgba(144,144,153,1)',
                formatter: function() {
                  return '';
                }
              },
              lineStyle: {
                normal: {
                  type: 'dashed',
                  color: 'rgba(244, 67, 54, 1)'
                }
              },
              data: [
                {
                  yAxis: temp_line,
                  name: '10摄氏度'
                }
              ]
            }
          },
          {
            name: '摄氏度(℃)(10CM)（预测线）',
            type: 'line',
            yAxisIndex: 0,
            smooth: false, // 关键点，为true是不支持虚线，实线就用true
            itemStyle: {
              normal: {
                lineStyle: {
                  type: 'dotted',
                  color: 'rgba(50,196,94,1)'
                }
              }
            },
            data: ydataAAFuture
          },
          {
            name: '摄氏度(℃)(40CM)（预测线）',
            type: 'line',
            yAxisIndex: 0,
            itemStyle: {
              normal: {
                lineStyle: {
                  type: 'dotted',
                  color: 'rgba(255,167,28,1)'
                }
              }
            },
            data: ydataBBFuture
          }
        ]
      };

      /**
       * 竖向标记线
       */
      if (marklineArr && marklineArr.length) {
        var marklineStart, marklineEnd;
        for (var i = 0; i < marklineArr.length; i++) {
          var marklinePoint = marklineArr[i];
          if (marklinePoint == 1 && !(marklineStart == 0 || marklineStart)) {
            marklineStart = i;
            continue;
          }
          if (marklinePoint == 1 && !(marklineEnd == 0 || marklineEnd)) {
            marklineEnd = i;
            break;
          }
        }

        // 即有起始点，也有终止点时，
        // 绘制阴影面积和竖向折线
        if (
          (marklineStart == 0 || marklineStart) &&
          (marklineEnd == 0 || marklineEnd)
        ) {
          var ydataAALine = [];
          if (ydataA) {
            for (var k = 0; k < ydataA.length; k++) {
              var arr__ = (ydataA[k] - 273.15).toFixed(2);
              if (k >= marklineStart && k <= marklineEnd) {
                ydataAALine.push(arr__);
                continue;
              }
              if (k < marklineStart) {
                ydataAALine.push('');
              }
              if (k > marklineEnd) {
                break;
              }
            }
          }

          option['series'].push({
            name: '摄氏度(℃)(40CM)（竖线）',
            type: 'line',
            yAxisIndex: 0,
            itemStyle: {
              normal: {
                lineStyle: {
                  type: 'solid',
                  color: 'rgba(50,196,94,1)'
                }
              }
            },
            data: ydataAALine,
            areaStyle: {
              color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(50, 196, 94,0.15)'
                },
                {
                  offset: 1,
                  color: 'rgba(50, 196, 94,0.05)'
                }
              ])
            },
            markLine: {
              symbol: 'none',
              lineStyle: {
                normal: {
                  type: 'dashed',
                  color: 'rgba(244, 67, 54, 1)'
                }
              },
              label: {
                show: false
              },
              emphasis: {
                label: {
                  show: false
                }
              },
              data: [
                {
                  xAxis: marklineStart
                },
                {
                  xAxis: marklineEnd
                }
              ]
            }
          });

          var visualMap = {
            type: 'piecewise',
            show: false,
            dimension: 0,
            seriesIndex: 4,
            pieces: [
              {
                gt: marklineStart,
                lt: marklineEnd - 1,
                color: 'rgba(0, 180, 0, 0.5)'
              }
            ]
          };

          option['visualMap'] = visualMap;
        }
      }

      if (option && typeof option === 'object') {
        myChartscen.clear();
        myChartscen.setOption(option, false);
        this.chartRenderedTemp(myChartscen);
      }
    },
    chartRenderedTemp(myChart) {
      var currentOption = myChart.getOption();
      var xAxisDataCur = currentOption.xAxis[0].data;
      for (var i = 0; i < xAxisDataCur.length; i++) {
        var xItem = xAxisDataCur[i].toString();
        var year = xItem.substr(0, 4);
        var month = xItem.substr(4, 2);
        var monthFormat = month.substr(0, 1) == 1 ? month : month.substr(1, 1);
        var day = xItem.substr(6, 2);
        var curYear = new Date().getFullYear();
        var curMonth = new Date().getMonth() + 1;
        var curDay = new Date().getDate();
        if (curYear == year && curMonth == monthFormat && curDay == day) {
          myChart.dispatchAction({
            type: 'highlight',
            seriesIndex: 0,
            dataIndex: i
          });
          myChart.dispatchAction({
            type: 'showTip',
            seriesIndex: 0,
            dataIndex: i
          });
          break;
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.echartsBox {
  width: 100%;
  flex: 1;
  position: relative;
  display: flex;
  flex-direction: column;
  .nav {
    width: 100%;
    height: 48px;
    padding: 10px 40px 0;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    white-space: nowrap;
    overflow: hidden;

    .select {
      margin-left: 13px;
      width: 68px;
      height: 21px;
      border-radius: 1px;
      border: 1px solid #32c45e;
      font-size: 12px;
      font-weight: 400;
      color: #32c45e;
      padding: 0 4px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .nav_left {
      font-size: 12px;
      font-weight: 400;
      line-height: 16px;
      color: #909099;
      opacity: 1;
      display: flex;
      align-items: center;
      position: relative;

      .van-icon-play {
        position: absolute;
        display: block;
        width: 13px;
        height: 13px;
        right: -8px;
        top: 2px;
        font-size: 15px;
        color: #32c45e;
        transform-origin: 0px 0px;
        transform: rotate(90deg);
      }

      select::-ms-expand {
        display: none;
      }
    }

    .legend_item {
      display: flex;
      align-items: center;

      .item_icon_green {
        width: 11px;
        height: 11px;
        border-radius: 50%;
        background-color: #32c45e;
      }

      .item_icon_orange {
        width: 11px;
        height: 11px;
        border-radius: 50%;
        background-color: #ffa71c;
      }

      .desc {
        margin-left: 5px;
      }

      margin-right: 13px;
    }

    .nav_right {
      font-size: 12px;
      font-weight: 400;
      line-height: 16px;
      color: #909099;
      opacity: 1;
      display: flex;
      align-items: center;
    }
  }
  .echarts {
    width: 100%;
    flex: 1;
  }
}
</style>
